#include "head.h"

int main(void)
{
    int sock_fd;
    tcp(&sock_fd, IP, PORT);

    int epoll_fd = epoll_create(1);
    epoll_add(epoll_fd, sock_fd);
    epoll_add(epoll_fd, STDIN_FILENO);

    fprintf(stderr,"请输入文件名: ");
    FileName_t file_name;

    while(1)
    {
        struct epoll_event events[2];
        bzero(events, sizeof(events));
        int count = epoll_wait(epoll_fd, events, 2, -1);
        for(int i = 0; i < count; ++i)
        {
            int current_fd = events[i].data.fd;
            if(current_fd == STDIN_FILENO)
            {
                bzero(&file_name, sizeof(file_name));
                char buf[30] = {0};
                int count = read(STDIN_FILENO, buf, sizeof(buf));
                strncpy(file_name.name, buf, count - 1);
                send(sock_fd, &file_name, sizeof(file_name), 0);
            }
            else
            {
                struct stat statbuf;
                int ret = recv(sock_fd, &statbuf, sizeof statbuf, MSG_WAITALL);
                if(ret == 0)
                    break;
                off_t file_size = statbuf.st_size;
                int file_fd = open(file_name.name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
                ftruncate(file_fd, file_size);
                float num = 0;
                while(1)
                {
                    char buf[1024] = {0};
                    int count = recv(sock_fd,buf, sizeof(buf), 0);
                    write(file_fd, buf, count);
                    num += count;
                    fprintf(stderr, "\r下载进度: %-4.2f%%", num / file_size * 100);
                    if(file_size == num)
                        break;
                }
                printf("\n");
                fprintf(stderr, "下载成功\n");
                close(file_fd);
                file_hash(file_name.name);
                fprintf(stderr, "请输入文件名: ");
            }
        }
    }


    close(sock_fd);
    return 0;
}
